package logic

import (
	"context"
	"errors"
	"shop-cart/cache"
	"shop-cart/models"
	"strconv"

	"shop-cart/taobaorpc/internal/svc"
	"shop-cart/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CarListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCarListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CarListLogic {
	return &CarListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CarListLogic) CarList(in *taobaorpc.CarListRequest) (*taobaorpc.CarListResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	data, err := user.FindUserById(models.DB, in.UserId)
	if err != nil {
		return nil, err
	}
	if data.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	keys, err := cache.FindCartKeys(in.UserId)
	if err != nil {
		return nil, err
	}
	var allPrice float64
	var carLists []*taobaorpc.CarList
	for _, key := range keys {
		product, _ := cache.FindCartProduct(key)
		price, _ := strconv.ParseFloat(product["price"], 64)
		userId, _ := strconv.Atoi(product["userId"])
		productId, _ := strconv.Atoi(product["productId"])
		number, _ := strconv.Atoi(product["number"])
		singlePrice := price * float64(number)
		allPrice += singlePrice
		carList := &taobaorpc.CarList{
			Title:       product["title"],
			Price:       float32(price),
			Image:       product["image"],
			UserId:      int64(userId),
			ProductId:   int64(productId),
			Number:      int64(number),
			SinglePrice: float32(singlePrice),
		}
		carLists = append(carLists, carList)
	}
	return &taobaorpc.CarListResponse{
		List:     carLists,
		AllPrice: float32(allPrice),
	}, nil
}
